from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
from config.database_connect import get_db_connection

appRegister = APIRouter()

class UserRegister(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
    password: str = Field(..., min_length=6, max_length=100)

@appRegister.post("/api/register", status_code=status.HTTP_201_CREATED)
async def register(user_data: UserRegister):
    db = get_db_connection()
    if not db:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            detail="数据库连接失败")
    try:
        with db.cursor() as cursor:
            # 检查用户名是否已存在
            cursor.execute("SELECT id FROM users WHERE username = %s", (user_data.username,))
            if cursor.fetchone():
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                                    detail="用户名已存在")
            # 创建新用户（明文密码存储—注意这是不安全的，只在你确认这种场景下使用）
            cursor.execute(
                "INSERT INTO users (username, password) VALUES (%s, %s)",
                (user_data.username, user_data.password)
            )
            db.commit()
            return {"status": "success", "message": "注册成功", "username": user_data.username}
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            detail=f"注册失败: {str(e)}")
    finally:
        db.close()
